#include "http.hpp"

std::string req_to_str(const HttpRequest &req) 
{
    std::stringstream tmp;
    tmp << "<html><body>";
    tmp << "<p>method:" << req.method << "</p>";
    tmp << "<p>path:" << req.path << "</p>";
    for (auto &it:req.matches) {
        tmp << "<p>matches:" << it << "</p>";
    }
    for (auto &it:req.params) {
        tmp << "<p>param: " << it.first << "=" <<  it.second << "</p>";
    }
    for (auto &it:req.headers) {
        tmp << "<p>header: " << it.first << ": " <<  it.second << "</p>"; 
    }
    tmp << "<p>" << req.body << "</p>";
    tmp << "</body></html>";
    return tmp.str();
}

void HelloWorld(const HttpRequest &req, HttpResponse *rsp)
{
    std::string body = req_to_str(req);
    rsp->set_content(body, "text/html");
}
void Login(const HttpRequest &req, HttpResponse *rsp)
{
    std::string body = req_to_str(req);
    rsp->set_content(body, "text/html");
}
void Param(const HttpRequest &req, HttpResponse *rsp) 
{
    std::string body = req_to_str(req);
    rsp->set_content(body, "text/html");
}
void Put(const HttpRequest &req, HttpResponse *rsp) 
{
    //std::string body = req_to_str(req);
    //rsp->set_content(body, "text/html");
    std::string path = "./wwwroot" + req.path;
    DBG_LOG("BIG FILE: %s", path.c_str());
    Util::write_file(path, req.body);
}
void Delete(const HttpRequest &req, HttpResponse *rsp) 
{
    std::string body = req_to_str(req);
    rsp->set_content(body, "text/html");
}
void http_test() {
    bit_net::EventLoop loop;
    HttpServer server(&loop, 8500);
    server.set_thread_count(3);
    server.set_base_dir("./wwwroot");
    server.Get("/hello", HelloWorld);
    server.Get("/params", Param);
    server.Post("/login", Login);
    server.Put("/\\S+", Put);
    server.Delete("/delete/(\\d+)", Delete);
    server.start();
    loop.start();
}

int main()
{
    http_test();
    return 0;
}

